package com.wh.wisdomsite.xbox.utils;

import com.wh.wisdomsite.xbox.utils.media.Multimedia;
import org.apache.commons.io.FilenameUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class Utils {


    /**
     * 验证对象是否为NULL,空字符串，空数组，空的Collection或Map(只有空格的字符串也认为是空串)
     * @param obj 被验证的对象
     * @param message 异常信息
     */
	public static void notEmpty(Object obj, String message) {
		if (obj == null){
			throw new IllegalArgumentException(message + " must be specified");
		}
		if (obj instanceof String && obj.toString().trim().length()==0){
			throw new IllegalArgumentException(message + " must be specified");
		}
		if (obj.getClass().isArray() && Array.getLength(obj)==0){
			throw new IllegalArgumentException(message + " must be specified");
		}
		if (obj instanceof Collection && ((Collection)obj).isEmpty()){
			throw new IllegalArgumentException(message + " must be specified");
		}
		if (obj instanceof Map && ((Map)obj).isEmpty()){
			throw new IllegalArgumentException(message + " must be specified");
		}
	}


    /**
	 * 将空对象返回为空字符串
	 * 
	 * @param obj
	 * @return
	 */
	public static String getStr(Object obj) {
		if (obj == null) {
			return "";
		} else {
			return String.valueOf(obj);
		}
	}
    /**
     * 将空对象返回为空字符串
     *
     * @param obj
     * @return
     */
    public static String getString(Object obj) {
        return getStr(obj);
    }
    /**
     * 将空对象返回为空字符串
     *
     * @param obj
     * @return
     */
    public static boolean isNotEmpty(Object obj) {
        if (obj == null) {
            return false;
        }
        if(getStr(obj).replaceAll(" ","").trim().equals("")){
            return false;
        }
        return true;
    }

    public static boolean isEmpty(Object obj) {
        if (obj == null) {
            return true;
        }
        if(getStr(obj).replaceAll(" ","").trim().equals("")){
            return true;
        }
        return false;
    }
	
	/**
	 * 将空对象返回为空字符串
	 * 
	 * @param obj
	 * @return
	 */
	public static String getStr(Object obj,String def) {
		String s=getStr(obj);
		if (s.equals("")) {
			return def;
		} else {
			return String.valueOf(obj);
		}
	}



    /**
     * 将空对象返回为null
     *
     * @param obj
     * @return
     */
    public static Integer getInteger(Object obj) {
        String s=getStr(obj);
        if (s.equals("")) {
            return null;
        } else {
            return Integer.valueOf(String.valueOf(obj));
        }
    }

	/**
	 * 将空对象返回为0
	 * 
	 * @param obj
	 * @return
	 */
	public static int getInt(Object obj) {
		String s=getStr(obj);
		if (s.equals("")) {
			return 0;
		} else {
			return Integer.parseInt(String.valueOf(obj));
		}
	}
	
	/**
	 * 将空对象返回为0
	 * 
	 * @param obj
	 * @return
	 */
	public static int getInt(Object obj,int def) {
		if (obj == null) {
			return def;
		} else {
			return Integer.parseInt(String.valueOf(obj));
		}
	}
	
	/**
	 * 返回
	 * @param code
	 * @param message
	 * @param navTabId 如果是失败则不需要填写
	 * @return
	 */
	public static String getMessage2client(String code, String message, String navTabId){
		String jsonStr = "";
		if(code != null && code.equals("200")) {
			jsonStr = "{\"statusCode\":\"" + code + "\", \"message\":\"" + message + "\",\"navTabId\":\"" + navTabId + "\", \"forwardUrl\":\"\",\"callbackType\":\"closeCurrent\"}";
		} else {
			jsonStr = "{\"statusCode\":\"" + code + "\", \"message\":\"" + message + "\"}";
		}
		
		return jsonStr;
	}
	
	
	/**
	 * 验证码验证，将页面得到的字符串进行验证
	 * @param req
	 * @param code 需要验证的字符串
	 * @return
	 */
	public static boolean isVerifyCode(HttpServletRequest req,String code){
		String fromCode=Utils.getStr(code);
		String ServerCode=Utils.getStr(req.getSession().getAttribute("verifyCode"));
		if(fromCode.equals("")){return false;}
		if(fromCode.toLowerCase().equals(ServerCode.toLowerCase())){
	    	return true;
	    }else{
	    	return false;
	    }  
	}
	
	/**
	 * 验证码验证，页面上需验证的控件名为verifyCode时，将自动得到值进行验证
	 * @param req
	 * @return
	 */
	public static boolean isVerifyCode(HttpServletRequest req){
		String fromCode=Utils.getStr(req.getParameter("verifyCode"));
		return isVerifyCode(req,fromCode);
	}

    /**
     * 得到当前登录ID
     * @param req
     * @return
     */
    public static String getLoingId(HttpServletRequest req){
       return getStr(req.getSession().getAttribute("loginuserid"));
    }

    public static String  getDateStr(Date date){
        if(null == date){
            return "";
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return dateFormat.format(date);
    }

    public static String  getLongDateStr(Date date){
        if(null == date){
            return "";
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //return dateFormat.getDateTimeInstance().format(date);  //在jdk6下不支持
        return dateFormat.format(date);
    }

    public static Date getDate(String source) {
        if(getStr(source).equals("")){return null;}

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        if(source.length() > 10){
            dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
        dateFormat.setLenient(false);
        try {
            return dateFormat.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
            throw new RuntimeException("日期格式错误");
        }
    }


    public static String getDateNum(Date date){
        if(null == date){
            return "";
        }
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        return dateFormat.format(date);
    }


    public static String getProperties(String key){
        InputStream inputStream = Utils.class.getClassLoader().getResourceAsStream("conf/application.properties");
        Properties p = new Properties();
        try {
            p.load(inputStream);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return p.getProperty(key);
    }


    /****
     * 将字符拆分成in 条件
     * @param criteria
     * @return
     */
    public static String addCriterionByCriteria(String criteria){
        String[] strs = criteria.split(",");
        if(strs.length <= 1){
            return "'"+criteria+"'";
        }else{
            String str = "";
            for(int i = 0; i< strs.length; i++){
                str += "'"+strs[i]+"',";
            }
            if (str.length() > 0 ) str = str.substring(0, str.length() - 1);
            return str;
        }
    }

    /****
     * 将字符拆分成in 条件
     * @param criteria
     * @return
     */
    public static String addCriterionByCriteria(List<String> criteria){

        if(criteria.size()==0){
            return null;
        }

        if(criteria.size() <= 1){
            return "'"+criteria.get(0)+"'";
        }else{
            String str = "";
            for(int i = 0; i< criteria.size(); i++){
                str += "'"+criteria.get(i)+"',";
            }
            if (str.length() > 0 ) str = str.substring(0, str.length() - 1);
            return str;
        }
    }




    /**
     * 文件下载响应头设置
     * @param request
     * @param response
     * @param file
     * @param saveName
     */
    public static void setFileDownloadHeader(
            HttpServletRequest request,HttpServletResponse response,File file,String saveName
    ){
        if(file==null){
            throw new RuntimeException("传入数据异常");
        }
        response.setContentLength((int) file.length());
        setFileDownloadHeader(response, request, file.getName(), saveName);
    }
    //
    public static void setFileDownloadHeader(
            HttpServletResponse response,HttpServletRequest request,String fileName,String saveName
    ){
        String ext = FilenameUtils.getExtension(fileName);
        String mine_type = Multimedia.mime_types.get(ext);
        if (mine_type != null) {
            response.setContentType(mine_type);
        }

        String new_filename = saveName;
        try{
            new_filename = URLEncoder.encode(saveName, "UTF8");
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }

        // 如果没有UA，则默认使用IE的方式进行编码，因为毕竟IE还是占多数的
        String ua = request.getHeader("user-agent");
        if (ua != null && ua.indexOf("Firefox") >= 0) {
            response.setHeader("Content-Disposition", "attachment; filename*=\"UTF-8''" + new_filename + "\"");
        } else {
            response.setHeader("Content-Disposition", "attachment; filename=" + new_filename);
        }
    }


    /**
     * 招商贷交易流水号
     * @return
     */
    public static String GetZsdSerialNo(){
        //14位时间/10 = 12时间 + 7位随机数
        String nowTime = ((new Date().getTime() / 10) + new Random().nextInt(9999999)) + "";
        //两位随机数
        String lastNo = ((int)(Math.random() * 90 + 10)) + "";
        return "YB" + nowTime + lastNo;
    }




}
